package com.csx.micrometer.invoke.context;

import org.springframework.util.LinkedCaseInsensitiveMap;

import java.util.HashMap;
import java.util.Map;

/**
 * @author cuisongxu
 * @date 2022/12/3 17:11
 */
public abstract class MicrometerResponse implements MicrometerMessage{

    protected Object originResponse;

    /**
     * 请求对象属性缓存
     */
    protected Map<String, Object> attributesCache = new HashMap<>();

    protected Map<String, String> headers = new LinkedCaseInsensitiveMap<>();

    public MicrometerResponse(Object originResponse) {
        this.originResponse = originResponse;
    }

    public Object getOriginResponse() {
        return originResponse;
    }

    public void setOriginResponse(Object originResponse) {
        this.originResponse = originResponse;
    }


    @Override
    public Object getAttribute(String key) {
        return this.attributesCache.get(key);
    }

    @Override
    public MicrometerMessage setAttribute(String key, Object value) {
        this.attributesCache.put(key, value);
        return this;
    }

    @Override
    public void removeAttribute(String key) {
        this.attributesCache.remove(key);
    }

    @Override
    public Map<String, Object> getAttributes() {
        return this.attributesCache;
    }

    @Override
    public void setHeader(String name, String value) {
        headers.put(name, value);
    }

    @Override
    public <T> T getOriginMessage(Class<T> desiredType) {
        if(desiredType == null) {
            return null;
        }
        Object originResponse = getOriginResponse();
        if(desiredType.isInstance(originResponse)) {
            return desiredType.cast(originResponse);
        }
        return null;
    }
}
